package com.aracky.system.controller;

import com.aracky.common.constants.LoginConstants;
import com.aracky.common.util.ConvertUtil;
import com.aracky.common.vo.CommonResult;
import com.aracky.common.vo.PageVO;
import com.aracky.system.model.entity.SysUser;
import com.aracky.system.model.entity.SysUserRole;
import com.aracky.system.model.form.SysUserForm;
import com.aracky.system.model.form.SysUserRoleForm;
import com.aracky.system.model.request.SysUserRequest;
import com.aracky.system.model.vo.SysUserVO;
import com.aracky.system.service.SysUserRoleService;
import com.aracky.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author zzp
 * @since 2022-07-14 11:22:57
 */
@RestController
@RequestMapping("/sysUser")
@Api(tags = "用户相关接口")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 用户列表查询
     * @param sysUserRequest
     * @return
     */
    @ApiOperation(value = "用户分页查询")
    @PostMapping(value = "/pageList")
    public CommonResult<PageVO<SysUserVO>> pageList(@RequestBody SysUserRequest sysUserRequest){
        PageVO<SysUserVO> pageVO=sysUserService.getUserPage(sysUserRequest);
        return CommonResult.success(pageVO);
    }



    /**
     * 用户新增
     * @return
     */
    @ApiOperation(value = "新增")
    @PostMapping("/save")
    public <T> CommonResult<T> save(@RequestBody SysUserForm sysUserForm) {
        if(sysUserService.getCheckLoginName(sysUserForm.getLoginName())>0){
            return CommonResult.error("用户已存在!");
        }else if(sysUserService.getCheckByEmail(sysUserForm.getEmail())>0){
            return CommonResult.error("邮箱已存在!");
        }else if(sysUserService.getCheckPhone(sysUserForm.getPhonenumber())>0){
            return CommonResult.error("电话号码已存在!");
        }
        SysUser sysUser = ConvertUtil.sourceToTarget(sysUserForm, SysUser.class);
        String encode = passwordEncoder.encode(LoginConstants.USER.DEFAULT_PASWORD);
        sysUser.setPassword(encode);
        boolean result = sysUserService.save(sysUser);
        if (result) {
            return CommonResult.success("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    /**
     * 用户修改
     * @param sysUserForm
     * @param <T>
     * @return
     */
    @ApiOperation(value = "修改")
    @PutMapping("/update")
    public <T> CommonResult<T> update(@RequestBody SysUserForm sysUserForm){
        LambdaQueryWrapper<SysUser> lambdaQueryWrapper
                = Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId,sysUserForm.getUserId());
        SysUser sysUser=sysUserService.getOne(lambdaQueryWrapper);
        if(sysUserService.getCheckByEmail(sysUserForm.getEmail())>0 && !sysUser.getEmail().equals(sysUserForm.getEmail())){
            return CommonResult.error("邮箱已存在!");
        }else if(sysUserService.getCheckPhone(sysUserForm.getPhonenumber())>0 && !sysUser.getPhonenumber().equals(sysUserForm.getPhonenumber())){
            return CommonResult.error("电话号码已存在!");
        }
        int result=sysUserService.update(ConvertUtil.sourceToTarget(sysUserForm,SysUser.class));
        if(result>0){
            return CommonResult.success("操作成功");
        }
        return CommonResult.error("操作失败");
    }

    /**
     * 用户删除
     * @param
     * @return
     */
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{userIds}")
    public CommonResult delete(@PathVariable Long[] userIds){
        List<Long> list=new ArrayList<>();
        for (Long userId:userIds){
            list.add(userId);
        }
        sysUserService.removeBatchByIds(list);
        return CommonResult.success("操作成功");
    }

    /**
     * 用户详情查询
     * @param userId
     * @return
     */
    @ApiOperation(value = "用户详情查询")
    @GetMapping("/{userId}")
    public CommonResult get(@PathVariable Long userId){
        SysUser sysUser=sysUserService.get(userId);
        SysUserVO sysUserVO=ConvertUtil.sourceToTarget(sysUser,SysUserVO.class);
        return CommonResult.success(sysUserVO,"操作成功");
    }

    /**
     * 分配角色给用户
     * @param sysUserRoleForm
     * @return
     */
    @ApiOperation(value = "分配角色给用户")
    @PostMapping("/bind/role")
    public CommonResult saveRole(@RequestBody SysUserRoleForm sysUserRoleForm){
        sysUserService.saveRole(sysUserRoleForm.getUserId(),sysUserRoleForm.getRoleIds());
        return CommonResult.success("操作成功");
    }

    @ApiOperation(value = "用户取消绑定角色")
    @DeleteMapping("/unbind/role")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户id"),
            @ApiImplicitParam(name = "roleId",value = "角色id")
    })
    public CommonResult delRole(Long userId,Long roleId){
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper
                = Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId)
                .eq(SysUserRole::getRoleId,roleId);
        sysUserRoleService.remove(lambdaQueryWrapper);
        return CommonResult.success("操作成功");
    }

}
